﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Common.Logging;
using TellStick;

namespace haunstm_test_telldus
{
    public class Demo
    {
        private ILog log;

        public Demo()
        {
            log = LogManager.GetLogger(this.GetType());
        }

        public void Start()
        {
            RemoveAllTellstickDevicesFromWinReg();
            Initialize();
            RegisterTellStickDevices();
            //TurnOnAllTellStickDevices();
            //TurnOffAllTellStickDevices();
        }

        public void RemoveAllTellstickDevicesFromWinReg()
        {
            var tellstickDevices = TellStick.Base.GetDevices();

            tellstickDevices.ToList().ForEach(d => d.Remove());

            log.Info("TellStick devices removed. Left: " + tellstickDevices.ToList().Count.ToString());
        }

        private void Initialize()
        {
            //tellstick
            TellStick.Base.SupportedMethods = TellStickMethods.TurnOn | TellStickMethods.TurnOff | TellStickMethods.Learn;

            log.Info("TellStick devices initialized");
        }

        private void RegisterTellStickDevices()
        {
            var registerableDevices = RegisterableDevices.Tellstics();
            foreach (var registerableDevice in registerableDevices)
            {
                registerableDevice.Save();

                log.Info("TellStick device saved: " + registerableDevice.Name);
            }
        }

        private void TurnOnAllTellStickDevices()
        {
            var registeredDevices = TellStick.Base.GetDevices();

            foreach (var registeredDevice in registeredDevices)
            {
                var turnOnTellStick = new ThreadStart(() => registeredDevice.TurnOn());
                var t = new Thread(turnOnTellStick);
                t.Name = registeredDevice.Name;
                t.Start();

                log.Info("TellStick device turned on qued: " + registeredDevice.Name);
            }
        }

        private void TurnOffAllTellStickDevices()
        {
            var registeredDevices = TellStick.Base.GetDevices();

            foreach (var registeredDevice in registeredDevices)
            {
                var turnOffTellStick = new ThreadStart(() => registeredDevice.TurnOff());
                var t = new Thread(turnOffTellStick);
                t.Name = registeredDevice.Name;
                t.Start();

                log.Info("TellStick device turned off qued: " + registeredDevice.Name);
            }
        }

    }

}
